package cn.lenqq.Utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

public class MybatisUtil {
    public static Logger log = Logger.getLogger(MybatisUtil.class.getName());

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            initPwdSecretTable();
        } catch (IOException e) {
            log.severe("初始化 SqlSessionFactory 发生异常" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static void initPwdSecretTable() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = """
                create table IF NOT EXISTS pwd_secret
                                    (
                                        id          INTEGER
                                            constraint pw_Info_pk
                                                primary key autoincrement,
                                        source      TEXT not null,
                                        cipher_text TEXT not null,
                                        sort        INTEGER,
                                        create_time INTEGER
                                    );
                """;
        Connection conn = sqlSession.getConnection();
        try {
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
            stmt.close();
            sqlSession.commit();
        } catch (SQLException e) {
            sqlSession.rollback();
            log.severe("初始化 pwd_secret 表发生异常" + e.getMessage());

        }finally {
            if(sqlSession != null) sqlSession.close();
        }

    }

}
